package cn.dslcode.security.common.service;

import cn.dslcode.security.common.DataCenter;
import cn.dslcode.security.common.SystemUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SystemUser userDetails = DataCenter.users.stream().filter(u -> u.getUsername().equals(username)).findFirst().orElse(null);
        log.info("userDetails={}", userDetails);
        if (userDetails == null) {
            throw new UsernameNotFoundException("");
        }
        if (userDetails.getAuthorities() == null) {
            // 角色的权限列表的权限
            Set<SimpleGrantedAuthority> grantedAuthorities = userDetails.getRoles().parallelStream().flatMap(
                role -> role.getAuths().stream().map(a -> new SimpleGrantedAuthority(a.getSecName()))
            ).collect(Collectors.toSet());
            // 角色权限
            grantedAuthorities.addAll(userDetails.getRoles().stream().map(role -> new SimpleGrantedAuthority(role.getSecName())).collect(Collectors.toSet()));
            userDetails.setAuthorities(grantedAuthorities);
        }
        return userDetails;
    }

}